<script setup lang="ts">
defineOptions({
  name: "chartsCheckbox"
});
import { deleteReportRecord } from "@/api/report";
import { onMounted, reactive, toRefs, ref, computed, nextTick, getCurrentInstance } from "vue";
import ReTextTooltip from "@/components/ReTextTooltip";
import { getReadersInZone, getReadersInZoneByType, getPointNewValue, queryChildByTypeCodeAndItemValue } from "@/api/machineClass";
import { queryScadaIndicator, getMeterReadingGroup, offlineIndicators } from "@/api/machineApi";
import { PxMessage, PxMessageBox } from "px-ui";
import { getEXHData } from "@/api/machineApi";
import { useRouter, useRoute } from "vue-router";
import { useNav } from "@/layout/hooks/useNav";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import lineChart from "@/views/machine/operation/environmentTestManage/components/lineChart/index.vue";
import dayjs from "dayjs";

interface Props {
  optionData?: any;
  /**  有 title 时传入 */
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  title 栏右侧文字 */
  rightText?: string | number;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  color?: string;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  ind?: number;
  className?: string;
  onlineKey?: string;
  leaveLineKey?: string;
  dateRange?: any;
}

const props = withDefaults(defineProps<Props>(), {
  width: 600,
  height: 468,
  boxShadow: false,
  borderRidus: false
});

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const { username } = useNav();
const router = useRouter();
const route = useRoute();

const templateUrl = ref();

const queryParams = reactive({
  year: new Date().getFullYear(),
  month: new Date().getMonth() + 1
});

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const midKey = ref(Date.now());

const pointsList = ref([]);
const keyTypeList = ref<any>([]);
const dataCodeList = ref([]);

const colorList1 = ["#4786FF", "#14C7C7", "#FFB266", "#8B8AE6", "#FFA299", "#2893EB"];

const colorList2 = ["#91B7FF", "#72DDDD", "#FFD1A4", "#BAB9F0", "#92CFF9", "#FFC7C1"];

const spcOptions = ref<any>({});
const checkList1 = ref<any>([]);
const checkList2 = ref<any>([]);
const pointsData1 = ref<any>([]);
const pointsData2 = ref<any>([]);

const pointsCurve = ref({});
const spcChartRef = ref<HTMLDivElement | null>(null);

let chartsInstance = null;

const spcChartsDom = ref(null);

const spcChartWeatherRef2 = ref(null);

// 在线指标列表
const getHotPointes = async () => {
  let arr = [];
  let str = props.onlineKey;
  const pointObj: any = await getMeterReadingGroup({
    groupCode: str,
    period: "HOUR"
  });
  if (pointObj.meterReadingItemList && pointObj.meterReadingItemList.length) {
    arr = pointObj.meterReadingItemList;
  }
  await getPointValue(arr, 1);
};

// 离线指标列表
const getHotPointes1 = async () => {
  let arr = [];
  let str = props.leaveLineKey;
  const pointObj: any = await offlineIndicators({
    location: str
  });
  if (pointObj && pointObj.length) {
    arr = pointObj;
  }
  const arrList =
    (arr &&
      arr.map((el: any) => {
        return {
          positionNum: el.measureCode,
          itemName: el.displayName,
          ...el
        };
      })) ||
    [];
  await getPointValue(arrList, 2);
};

// 获取点位实时数据(最大值、最小值、平均值)
const getPointValue = async (arr: any, val) => {
  if (!arr.length) return;
  const list = (arr && arr.map(item => item.positionNum)) || [];
  const res: any = await queryScadaIndicator({
    contentType: "LIST",
    bucketWidth: 1,
    bucketUnit: "hour",
    point: [...list],
    indicators: ["AVG", "MAX", "MIN", "FIRST", "LAST"],
    startTime: props.dateRange[0],
    endTime: props.dateRange[1]
  });
  // 第一组
  if (val === 1) {
    const pointList1: any = arr.map(item => {
      return {
        color1: colorList1[Math.floor(Math.random() * 6)],
        ...item
      };
    });
    pointList1.forEach((item: any) => {
      res.rows.forEach((el: any) => {
        if (item.positionNum === el.point) {
          Object.assign(item, el);
        }
      });
    });
    pointsData1.value = pointList1 || [];
    checkList1.value = [pointList1.length && pointList1[0].positionNum];
  } else {
    const pointList2: any = arr.map(item => {
      return {
        color1: colorList2[Math.floor(Math.random() * 6)],
        ...item
      };
    });
    pointList2.forEach((item: any) => {
      res.rows.forEach((el: any) => {
        if (item.positionNum === el.point) {
          Object.assign(item, el);
        }
      });
    });
    pointsData2.value = pointList2 || [];
    checkList2.value = [pointList2.length && pointList2[0].positionNum];
  }
};

// 多选1
const checkChange = val => {
  getEcharts();
};

const getActualWidthOfChars = (text, options: any = {}) => {
  const { size = 14, family = "Honeywell Sans Web, Verdana, sans-serif" } = options;
  let canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  ctx.font = `${size}px ${family}`;
  const metrics = ctx.measureText(text);
  const actual = Math.abs(metrics.actualBoundingBoxLeft) + Math.abs(metrics.actualBoundingBoxRight);
  canvas = null;
  return Math.max(metrics.width, actual);
};

// 查询报警明细
const getSpcCharts = async arr1 => {
  // const cwData = await queryChildByTypeCodeAndItemValue({
  //   value: "CWConfig",
  //   typeCode: "MCTS"
  // });
  // spcDataList.value = cwData ? cwData : [];
  // const jobIDs = [];
  // spcDataList.value.forEach((item: any) => {
  //   jobIDs.push(JSON.parse(item.itemDesc).spc_job);
  // });
  // 获取当前月份第一天
  const firstDayOfMonth = dayjs(new Date(queryParams.year, queryParams.month - 1, 1)).format("YYYY-MM-DD");
  // 获取当前月份最后一天
  const lastDayOfMonth = dayjs(new Date(queryParams.year, queryParams.month, 0)).format("YYYY-MM-DD");
  const params = {
    // taskType: "toc01",
    startTime: props.dateRange[0],
    endTime: props.dateRange[1],
    paramCode: dataCodeList.value[props.ind - 1]?.itemValue || "",
    // paramList: ["STIC_POWER_CONS_MV_TOTAL_KWH"],
    actualParamList: arr1,
    timePeriod: "minutes"
  };
  const res: any = await getEXHData(params);

  // 查询厂控线
  const pointData: any = await queryChildByTypeCodeAndItemValue({
    value: "NMHC_POINT",
    typeCode: "MCTS"
  });
  // const point1 = "22,11";
  // const point2 = "21,12";
  // const point3 = "11,22";
  // const point4 = "22,33";
  const point1 = pointData.find(item => item.itemValue === "MIC_EXHAUST_GRP1_NNMHC").itemDesc;
  const point2 = pointData.find(item => item.itemValue === "MIC_EXHAUST_GRP2_NNMHC").itemDesc;
  const point3 = pointData.find(item => item.itemValue === "MIC_EXHAUST_GRP3_NNMHC").itemDesc;
  const point4 = pointData.find(item => item.itemValue === "MIC_EXHAUST_GRP4_NNMHC").itemDesc;
  let str = "";
  switch (props.ind) {
    case 1:
      str = point1;
      break;
    case 2:
      str = point2;
      break;
    case 3:
      str = point3;
      break;
    case 4:
      str = point4;
      break;

    default:
      break;
  }

  // 预测数据
  const spcList0 = Object.keys(res[0]).map(e => {
    return {
      indicatorName: e,
      pointValues: res[0][e].map(item => {
        return {
          time: item.dateTimeResult,
          ...item
        };
      })
    };
  });
  // 实际数据
  const spcList1 = Object.keys(res[1]).map(e => {
    return {
      indicatorName: e,
      pointValues: res[1][e].map(item => {
        return {
          time: item.dateTimeResult,
          ...item
        };
      })
    };
  });
  const spcList = spcList0.concat(spcList1);
  console.log(spcList, "9999999999999999999999999");
  const obj: any = spcList[0] || {};

  const xData =
    obj.pointValues && obj.pointValues.length > 0
      ? obj.pointValues.map(item => formatDate(item.time))
      : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"];
  // weatherOptions.value = obj;

  let leftWidth = 0;
  let otherWidth = 0;

  let yAxis: any =
    spcList &&
    spcList.map((item, index) => {
      return {
        type: "value",
        position: index === 0 ? "left" : "right",
        // nameLocation: "middle", //居中
        // offset: index * 60,
        // nameGap: 70, //轴线距离
        // nameRotate: 90, //字体选择角度
        nameTextStyle: {
          // color: "#A0A0A0",
          fontSize: ".875rem",
          padding: index === 0 ? [0, 35, 15, 0] : [0, 0, 15, 40]
        },
        alignTicks: true,
        axisLine: {
          show: true,
          lineStyle: {
            type: "solid"
          }
        },
        axisLabel: {
          fontSize: ".875rem"
        }
      };
    });
  const series =
    spcList &&
    spcList.map((e, ind) => {
      return {
        // data: [400, 400, 400, 400, 400, 400],
        data: e.pointValues.length > 0 ? e.pointValues.map(item => (item.value ? Number(item.value) : item.value)) : [],
        type: "line",
        name: e.indicatorName,
        yAxisIndex: ind,
        areaStyle: {
          opacity: 0.15
        },
        // symbol: "none",
        showAllSymbol: true,
        markLine: {
          symbol: "none",
          data: [
            {
              name: "NMHC地标管控线",
              yAxis: Number(str.split(",")[0]),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `NMHC地标管控线${str.split(",")[0]}`,
                color: "#A600FF",
                fontWeight: 600
              }
            },
            {
              name: "NMHC厂控",
              yAxis: Number(str.split(",")[1]),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `NMHC厂控${str.split(",")[1]}`,
                color: "#FF0000",
                fontWeight: 600
              }
            }
          ]
        }
      };
    });
  series.forEach((el, index) => {
    const LeftExtend = [0, 0];
    const beforeLeftExtend = [0, 0];
    const data = el.data.filter(item => item !== "-").map(itme => parseFloat(itme)) || [];
    const beforeData = series[index - 1]?.data.filter(item => item !== "-").map(itme => parseFloat(itme)) || [];
    LeftExtend[1] = Math.max(...data) > LeftExtend[1] ? Math.max(...data) : LeftExtend[1];
    beforeLeftExtend[1] = Math.max(...beforeData) > beforeLeftExtend[1] ? Math.max(...beforeData) : beforeLeftExtend[1];
    const w = getActualWidthOfChars(Math.ceil(LeftExtend[1]).toString());
    const w1 = getActualWidthOfChars(Math.ceil(beforeLeftExtend[1]).toString());
    if (yAxis[index]) {
      yAxis[index].nameTextStyle = {
        // color: "#A0A0A0",
        fontSize: ".875rem",
        padding: index === 0 ? [0, w + 15, 15, 0] : [0, 0, 15, w + 15]
      };
      if (index !== 0) {
        otherWidth += Math.ceil(w) + 25;
      }
      if (index === 0 || index === 1) {
        yAxis[index].offset = 0;
      } else yAxis[index].offset = yAxis[index - 1].offset + Math.ceil(w1) + 25;
      if (yAxis.length === 2) otherWidth += 25;
      leftWidth = getActualWidthOfChars(xData[0]) / 2;
    }
  });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const option = {
    title: {
      text: props.title,
      textStyle: {
        fontSize: 16
      },
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    color: "#ccc",
    grid: {
      left: leftWidth + 5,
      top: "40px",
      right: otherWidth ? (otherWidth < 600 ? otherWidth : 600) : leftWidth + 25,
      bottom: "10%"
      // containLabel: true
    },
    dataZoom: [
      {
        show: false,
        realtime: true,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        realtime: true,
        start: 0,
        end: 100
      }
    ],
    legend: {
      type: "scroll",
      pager: {
        orient: "vertical",
        pageButtonItemGap: 5
      },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data: xData
    },
    yAxis: yAxis,
    series: series
  };
  spcOptions.value = option;
  midKey.value = new Date().getTime();
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

onMounted(async () => {
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "CIT02",
    typeCode: "MCTS"
  });
  // 废气指标
  const data1: any = await queryChildByTypeCodeAndItemValue({
    value: "MIC_EXHAUST_GROUP",
    typeCode: "MCTS"
  });
  dataCodeList.value = data1;
  keyTypeList.value = data.map(item => {
    return {
      type: JSON.parse(item.itemDesc).attr,
      unit: JSON.parse(item.itemDesc).unit,
      ...item
    };
  });
  await getHotPointes();
  // await getHotPointes1();
  console.log(checkList1.value, checkList2.value);
  if (checkList1.value.concat(checkList2.value).length > 0) {
    spcOptions.value = getSpcCharts([...checkList1.value.concat(checkList2.value)]);
    midKey.value = Date.now();
  }
});

const clickHandler = () => emits("btn-click");

const getEcharts = async () => {
  await nextTick();
  await getHotPointes();
  let arr = [];
  arr = checkList1.value.concat(checkList2.value);
  console.log(arr);
  if (!arr.length) {
    spcOptions.value = {};
    midKey.value = Date.now();
    return;
  }
  spcOptions.value = getSpcCharts(arr);
  midKey.value = Date.now();
};

const getEchartsDom = async () => {
  const echartsDom: any = await spcChartWeatherRef2.value.getEcharts();
  return echartsDom;
};

defineExpose({
  getEcharts,
  getEchartsDom
});
</script>

<template>
  <div class="chart-box" :class="{ boxShadow, borderRidus }">
    <!-- <barTitle :title="title" /> -->
    <div class="con_spc">
      <div class="spc_com">
        <!-- <spcCharts ref="spcChartsDom" :key="midKey" :width="600" :height="480" :optionData="spcOptions" color="#3B82F6" /> -->
        <lineChart ref="spcChartWeatherRef2" :key="midKey" :width="600" :height="480" :options="spcOptions" />
      </div>
      <px-scrollbar>
        <div class="scroll_checkbox">
          <barTitle title="在线检测指标" />
          <px-checkbox-group v-if="pointsData1.length" v-model="checkList1" @change="checkChange">
            <div v-for="item in pointsData1" :key="item.positionNum" class="area_item">
              <div class="area_top" :style="{ backgroundColor: item.color1 }">
                <div>
                  <px-checkbox :label="item.positionNum">{{ item?.itemName }}</px-checkbox>
                </div>
                <div class="point_name">
                  <ReTextTooltip :content="item.positionNum" />
                </div>
              </div>
              <div class="area_bottom">
                <div class="bottom_item item_num">
                  {{ item.first_value !== null && item.first_value !== undefined ? item.first_value : "-" }}
                </div>
                <div class="bottom_item item_num">
                  {{ item.last_value !== null && item.last_value !== undefined ? item.last_value : "-" }}
                </div>
                <div class="bottom_item item_text">
                  <div class="text">最大值</div>
                  <div class="num">
                    {{ item.max_value !== null && item.max_value !== undefined ? item.max_value : "-" }}
                  </div>
                </div>
                <div class="bottom_item item_text">
                  <div class="text">最小值</div>
                  <div class="num">
                    {{ item.min_value !== null && item.min_value !== undefined ? item.min_value : "-" }}
                  </div>
                </div>
                <div class="bottom_item item_text">
                  <div class="text">平均值</div>
                  <div class="num">
                    {{ item.avg_value !== null && item.avg_value !== undefined ? Math.floor(item.avg_value) : "-" }}
                  </div>
                </div>
              </div>
            </div>
          </px-checkbox-group>
          <div v-else class="empty-con">
            <px-empty :image-size="100" />
          </div>
        </div>
      </px-scrollbar>
      <!-- <px-scrollbar>
        <div class="scroll_checkbox">
          <barTitle title="离线检测指标" />
          <px-checkbox-group v-if="pointsData2.length" v-model="checkList2" @change="checkChange">
            <div v-for="item in pointsData2" :key="item.id" class="area_item">
              <div class="area_top" :style="{ backgroundColor: item.color1 }">
                <div>
                  <px-checkbox :label="item.positionNum">{{ item?.itemName }}</px-checkbox>
                </div>
                <div class="point_name">
                  <ReTextTooltip :content="item.positionNum" />
                </div>
              </div>
              <div class="area_bottom">
                <div class="bottom_item item_num">
                  {{ item.first_value !== null && item.first_value !== undefined ? item.first_value : "-" }}
                </div>
                <div class="bottom_item item_num">
                  {{ item.last_value !== null && item.last_value !== undefined ? item.last_value : "-" }}
                </div>
                <div class="bottom_item item_text">
                  <div class="text">最大值</div>
                  <div class="num">
                    {{ item.max_value !== null && item.max_value !== undefined ? item.max_value : "-" }}
                  </div>
                </div>
                <div class="bottom_item item_text">
                  <div class="text">最小值</div>
                  <div class="num">
                    {{ item.min_value !== null && item.min_value !== undefined ? item.min_value : "-" }}
                  </div>
                </div>
                <div class="bottom_item item_text">
                  <div class="text">平均值</div>
                  <div class="num">
                    {{ item.avg_value !== null && item.avg_value !== undefined ? Math.floor(item.avg_value) : "-" }}
                  </div>
                </div>
              </div>
            </div>
          </px-checkbox-group>
          <div v-else class="empty-con">
            <px-empty :image-size="100" />
          </div>
        </div>
      </px-scrollbar> -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chart-box {
  padding: 16px 24px;
  background-color: #fff;

  .con_spc {
    display: flex;
    justify-content: space-between;

    .spc_com {
      position: relative;
      flex: 1;

      .edit_form {
        display: flex;
        flex-flow: row nowrap;
        gap: 10px;
      }

      .edit_y1 {
        position: absolute;
        cursor: pointer;
      }
    }

    .scroll_checkbox {
      width: 350px;
      height: 552px;
      margin-left: 8px;

      .point_name {
        width: 230px;
        font-size: 12px;
      }

      .empty-con {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: calc(100% - 32px);
      }

      .area_item {
        margin-bottom: 8px;
        font-size: 14px;
        border: 1px solid #dcdcdc;
        border-radius: 3px;

        .area_top {
          display: flex;
          justify-content: space-between;
          height: 36px;
          padding: 0 16px;
          line-height: 36px;
          white-space: nowrap;
          border-radius: 3px 3px 0 0;
        }

        .area_bottom {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 36px;
          padding: 5px 16px;
          line-height: 1;
          border-radius: 0 0 2px 2px;

          .bottom_item {
            flex: 1;
            text-align: center;
            border-right: 1px solid #909399;
          }

          .bottom_item:last-child {
            border-right: none;
          }

          .item_num {
            line-height: 26px;
          }

          .item_text {
            display: flex;
            flex-direction: column;
            gap: 2px;
            justify-content: space-between;

            .text {
              font-size: 12px;
              color: #909399;
            }

            .num {
              font-size: 12px;
            }
          }
        }
      }
    }
  }

  .echarts-chart-com {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: calc(100% - v-bind(title_height));
    border: 1px solid #dcdcdc;
  }
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}
</style>
